package com.fingersoft.im.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.fingersoft.api.ApiUtils;
import com.fingersoft.business.BusinessContext;
import com.fingersoft.business.contact.IContactProvider;
import com.fingersoft.business.im.IIMProvider;
import com.fingersoft.common.preference.AppPreferenceHelper;
import com.fingersoft.common.preference.UserAppPreferenceHelper;
import com.fingersoft.common.preference.provider.UserIdProvider;
import com.fingersoft.feature.personal.api.EnterConfig;
import com.fingersoft.feature.userinfo.model.User;
import com.fingersoft.im.R;
import com.fingersoft.im.api.UserAgent;
import com.fingersoft.im.api.base.AbsCallbackWithDeviceCheck;
import com.fingersoft.im.api.base.BaseResponse2;
import com.fingersoft.im.api.base.BaseResponsei3;
import com.fingersoft.im.api.model.UserInfo;
import com.fingersoft.im.constant.PreferenceKey;
import com.fingersoft.im.event.EventManager;
import com.fingersoft.im.model.TokenInfo;
import com.fingersoft.util.DeviceHelper;
import com.lzy.okgo.OkGo;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import cn.fingersoft.util.BuildConfigUtil;

@Deprecated
public class AppUtils {
    @NonNull
    @Deprecated
    public static Application application;
    public static String BASE_API_URL;
    public static String BASE_H5_URL;

    /**
     * @deprecated use CommonContext.getCommonCheckApiCallback().eCode
     */
    @Deprecated
    public static String J_ECODE;
    public static String RONG_NAV;
    private static String RONG_IMAGE;
    /**
     * 根据zone切换时，表示SaServer
     */
    private static String RONG_IMAGE_Sa;
    /**
     * if 'SgServer' eq zone then var fileServer='首钢文件地址'
     * else if 'SaServer' eq zone then fileServer='股份融云文件服务器地址'
     * SgServer使用改配置
     */
    private static String RONG_IMAGE_Sg;
    public static String MDM_HOST;
    public static  boolean DEBUG;
    public static String BASE_SOCKET_URL;
    public static String workTab_title;
    public static String moreTab_title;
    public static String newsTab_title;
    @NonNull
    private static Class buildConfigClass;
    private static ApiUtils utils;

    public static void init(@NonNull Application application, @NonNull Class buildConfigClass) {
        utils = new ApiUtils(application);
        AppUtils.application = application;
        AppUtils.buildConfigClass = buildConfigClass;
        BASE_API_URL = getString("BASE_API_URL", "").trim();
        BASE_H5_URL = getString("BASE_H5_URL", "").trim();
        J_ECODE = getString("J_ECODE", "").trim();
        RONG_NAV = getString("RONG_NAV", "").trim();
        RONG_IMAGE = getString("RONG_IMAGE", "").trim();
        MDM_HOST = getString("MDM_HOST", "").trim();
        BASE_SOCKET_URL = getString("BASE_SOCKET_URL", "").trim();
        DEBUG = getBoolean("DEBUG");
        workTab_title = getString("workTab_title", "").trim();
        moreTab_title = getString("moreTab_title", "").trim();
        newsTab_title = getString("newsTab_title", "").trim();
        if (TextUtils.isEmpty(RONG_IMAGE_Sg)) {
            RONG_IMAGE_Sg = RONG_IMAGE;
        }
        if (TextUtils.isEmpty(RONG_IMAGE_Sa)) {
            RONG_IMAGE_Sa = RONG_IMAGE;
        }
        LogUtils.i("BASE_API_URL=" + BASE_API_URL);

        //最后，切换企业配置
        AppUtils.Enterinit();
    }

    /**
     * @deprecated use BusinessContext.enterpriseConfigProvider.applyEnterpriseConfig()
     */
    @Deprecated
    public static void Enterinit() {
        BASE_API_URL = BuildConfigUtil.INSTANCE.getString("BASE_API_URL", "").trim();
        J_ECODE = BuildConfigUtil.INSTANCE.getString("J_ECODE", "").trim();

        EnterConfig ec=getEnterConfig();
        if(ec.getHost()!=null&&!ec.getHost().isEmpty()){
            BASE_API_URL=ec.getHost();
        }
        if(ec.getEcode()!=null&&!ec.getEcode().isEmpty()){
            J_ECODE=ec.getEcode();
        }
    }

    public static String getApiUrl(String apiUrl) {
        return getApiUrl(apiUrl, AppUtils.getTokenInfo().getAppPath());
    }

    public static String getApiUrl(String apiUrl, String appPath) {
        boolean empty = TextUtils.isEmpty(apiUrl);
        if (empty) {
            return "";
        }

        if (apiUrl.startsWith("http://") || apiUrl.startsWith("https://")) {
            return apiUrl;
        } else {
            return TextUtils.isEmpty(appPath) ? BASE_API_URL + apiUrl : BASE_API_URL + appPath + "/" + apiUrl;
        }
    }

    public static String makeApiUrl(String api){
        return AppUtils.getApiUrl(api, AppUtils.J_ECODE);
    }

    public static String makeAppAgentInfo(){
        return JSONUtils.toJsonString(new UserAgent(AppUtils.getTokenInfo().getUserToken(), AppUtils.getTokenInfo().getDid()));
    }

    public static String makeAppAgentInfo(Context context){
        return JSONUtils.toJsonString(new UserAgent(AppUtils.getTokenInfo().getUserToken(), DeviceHelper.getDeviceID(context)));
    }

    // =======================User和TokenInfo信息=======================
    private static User mUser = null;
    private static TokenInfo mTokenInfo = null;
    private static EnterConfig mEnter = null;

    public static void saveTokenInfo(TokenInfo tokenInfo) {
        if (tokenInfo != null) {
            mTokenInfo = tokenInfo;
            new AppPreferenceHelper().putString(PreferenceKey.TOKEN_INFO, JSONUtils.toJsonString(tokenInfo));
        }
    }

    public static TokenInfo getTokenInfo() {
        if (mTokenInfo == null) {
            String json = getAppPreferenceHelper().getString(PreferenceKey.TOKEN_INFO, null);
            if (!TextUtils.isEmpty(json)) {
                mTokenInfo = JSONUtils.fromJsonString(json, TokenInfo.class);
            }
        }

        return mTokenInfo != null ? mTokenInfo : new TokenInfo();
    }

    public static void saveUser(User user) {
        if (user != null) {
            mUser = user;
            new AppPreferenceHelper().putString(PreferenceKey.USER_INFO, JSONUtils.toJsonString(user));
        }
    }

    /**
     * @return
     * @deprecated use BusinessContext.user.id
     */
    @Deprecated
    @NonNull
    public static User getUser() {
        if (mUser == null) {
            String json = getAppPreferenceHelper().getString(PreferenceKey.USER_INFO, null);
            if (!TextUtils.isEmpty(json)) {
                mUser = JSONUtils.fromJsonString(json, User.class);
            }
        }

        return mUser != null ? mUser : new User();
    }

    /**
     * @deprecated
     */
    @Deprecated
    public static void saveEnterConfig(@Nullable EnterConfig enter) {
        if (enter != null) {
            mEnter = enter;
            new AppPreferenceHelper().putString(PreferenceKey.ENTER_CONFIG, JSONUtils.toJsonString(enter));
        }
    }

    @NonNull
    public static EnterConfig getEnterConfig() {
        if (mEnter == null) {
            String json = getAppPreferenceHelper().getString(PreferenceKey.ENTER_CONFIG, null);
            if (!TextUtils.isEmpty(json)) {
                mEnter = JSONUtils.fromJsonString(json, EnterConfig.class);
            }
        }

        return mEnter != null ? mEnter : new EnterConfig();
    }

    public static void  setHas_start() {

        new AppPreferenceHelper().putBoolean(PreferenceKey.HAS_START, true);
    }

    public static boolean isHas_start() {

        return getAppPreferenceHelper().getBoolean(PreferenceKey.HAS_START, false);
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    public static boolean isLogged() {
        if (TextUtils.isEmpty(getUser().getUserId())) {
            return false;
        }
        if (TextUtils.isEmpty(getTokenInfo().getUserToken())) {
            return false;
        }
        return true;
    }

    public static void logout(Context context) {
        UserInfo userInfo = UserInfoManager.INSTANCE.getCurrentUserInfo();
        mUser = null;
        UserInfoManager.INSTANCE.saveCurrentUserInfo(null);
        mTokenInfo = null;
        User user = AppUtils.getUser();
        user.setPassword("");
        saveUser(user);
        saveTokenInfo(new TokenInfo());

        clearCookies(application);


        BusinessContext.Companion.getUser().onLogout(context, new com.fingersoft.business.user.UserInfo(userInfo.getId() == null ? "" : userInfo.getId(), userInfo.getImid(), userInfo.getName(), userInfo.getIcon(), userInfo.getCellPhone(), userInfo.getDeptId()));
    }

    public static void kickedOfflineByOtherClient(Context context) {
        logout(context);
        if (getBoolean("kickedOfflineToLoginAgain", false)) {
            //kickedOfflineToLoginAgain
            getUserAppPreferenceHelper().putBoolean("isJustLogout", true);

        } else {
            //kickedOfflineToLogin
            getAppPreferenceHelper().remove(PreferenceKey.CURRENT_USER_INFO); // 清空用户信息
        }
    }

    static UserAppPreferenceHelper getUserAppPreferenceHelper() {
        return new UserAppPreferenceHelper(new UserIdProvider() {
            @NotNull
            @Override
            public String getUserId() {
                return AppUtils.getUser().getUserId();
            }
        });
    }

    /**
     * @param response
     * @return
     * @deprecated use com.fingersoft.business.api.ApiUtils.INSTANCE.showApiSucceedErrorToast
     */
    @Deprecated
    public static boolean showApiSucceedErrorToast(BaseResponse2 response) {
        return com.fingersoft.business.api.ApiUtils.INSTANCE.showApiSucceedErrorToast(response);
    }

    @Deprecated
    public static boolean showApiSucceedErrorToast(@Nullable BaseResponsei3 response) {
        if (response == null || null == response.getResult()) {
            ToastUtils.show(R.string.request_error);
            return true;
        } else {
            return false;
        }
    }

    /**
     * onError
     */
    @Deprecated
    public static void showApiErrorToast() {
        utils.showApiErrorToast();
    }

    public static boolean checkDeviceEnableForApiBody(BaseResponse2 response) {
        if (response != null && !response.isSucceed()) {
            int code = response.getCode();
            if (code == AbsCallbackWithDeviceCheck.KICK_OFF_LINE) {
                EventBus.getDefault().post(new EventManager.OnRNLogout());
            }
        }

        return response == null || !response.isSucceed();
    }

    public static void clearCookies(Context context) {
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();

        OkGo.getInstance().getCookieJar().getCookieStore().removeAllCookie();
    }


    public static void updateUserIcon(String userIcon) {
        if (!TextUtils.isEmpty(userIcon) && userIcon.startsWith("http")) {
            User user = AppUtils.getUser();
            user.setEmpLivingPhoto(userIcon);
            AppUtils.saveUser(user);

            com.fingersoft.im.api.model.UserInfo userInfo = UserInfoManager.INSTANCE.getCurrentUserInfo();
            userInfo.setIcon(userIcon);
            UserInfoManager.INSTANCE.saveCurrentUserInfo(userInfo);

            IIMProvider im = BusinessContext.Companion.getIm();
            if (im != null) {
                im.refreshUser(user.getImid(), user.getRealName(), user.getEmpLivingPhoto());
            }
            IContactProvider contact = BusinessContext.Companion.getContact();
            if (contact != null) {
                contact.refreshContact(user.getUserId(), user.getRealName(), user.getEmpLivingPhoto());
            }
        }
    }

    /**
     * @param chooseContactActivity
     * @param targetUserId          userId
     * @param title
     */
    @Deprecated
    public static void startPrivateChat(Activity chooseContactActivity, String targetUserId, String title) {
        String imid = targetUserId;
        IContactProvider.UserInfo user = BusinessContext.Companion.getContact().getUserInfoById(targetUserId);
        if (null != user) {
            imid = user.getImid();
        }
        IIMProvider im = BusinessContext.Companion.getIm();
        if (im != null) {
            im.startPrivateChatByImid(chooseContactActivity, imid, title);
        }
    }


    // 版本更新后，重新登录模块 start
    private static String mOldVersion = null;

    public static boolean useGnet() {
        return BuildConfigUtil.INSTANCE.getBoolean("useGnet", false);
    }

    public static boolean useGnetInIMMenu() {
        return BuildConfigUtil.INSTANCE.getBoolean("useGnetInIMMenu", true);
    }

    public static boolean reloginWhenUpgrade() {
        return getBoolean("reloginWhenUpgrade");
    }

    public static String loginSubTitle() {
        return getString("sub_title","移动办公新时代");
    }

    public static boolean isUpgrade() {
        mOldVersion = getAppPreferenceHelper().getString(PreferenceKey.OLD_VERSION, null);
        return mOldVersion == null || !mOldVersion.equals(getString("VERSION_NAME", ""));
    }

    public static void recordVersion() {
        getAppPreferenceHelper().putString(PreferenceKey.OLD_VERSION, getString("VERSION_NAME", ""));
    }

    @NonNull
    private static AppPreferenceHelper getAppPreferenceHelper() {
        return new AppPreferenceHelper();
    }
    // 版本更新后，重新登录模块 end

    public static boolean getBoolean(String key, boolean defaultValue) {
        try {
            return Boolean.parseBoolean(
                (String) buildConfigClass.getField(key).get(null));
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.w("ApiUtils", String.format("BuildConfig.%s is not exist,use default value:%s", key, defaultValue));
            return defaultValue;
        }
    }

    public static boolean getBoolean(String key) {
        return getBoolean(key, false);
    }

    @NonNull
    public static String getString(@NonNull String key, @NonNull String defaultValue) {
        try {
            String value = (String) buildConfigClass.getField(key).get(null);
            return value != null ? value : defaultValue;
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.w("ApiUtils", String.format("BuildConfig.%s is not exist,use default value:%s", key, defaultValue));
            return defaultValue;
        }
    }

    public static long getLong(String key, long defaultValue) {
        try {
            String value = (String) buildConfigClass.getField(key).get(null);
            return Long.parseLong(value);
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.w("ApiUtils", String.format("BuildConfig.%s is not exist,use default value:%s", key, defaultValue));
            return defaultValue;
        }
    }

    public static int getInt(String key, int defaultValue) {
        try {
            String value = (String) buildConfigClass.getField(key).get(null);
            return Integer.parseInt(value);
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.w("ApiUtils", String.format("BuildConfig.%s is not exist,use default value:%s", key, defaultValue));
            return defaultValue;
        }
    }

    public static boolean isMDMEnable() {
        return getBoolean("MDMEnable");
    }

    public static boolean isScreenShotForbidden() {
        return BuildConfigUtil.INSTANCE.getBoolean("isScreenShotForbidden");
    }

    public static boolean useMdm() {
        return getBoolean("useMdm");
    }

    public static boolean EBenHandwritingEnabled() {
        return getBoolean("EBenHandwritingEnabled");
    }

    public static boolean useWorkcircle() {
        return getBoolean("useWorkcircle");
    }

    public static boolean loginAppNameIsCustomImg() {
        return getBoolean("loginAppNameIsCustomImg");
    }

    public static boolean useWelcome() {
        return getBoolean("useWelcome");
    }

    public static boolean useDeviceVerify() {
        return getBoolean("useVerifyDevicePolicy");
    }

    public static boolean isUsingSolidKey() {
        return getBoolean("useVerifyDevicePolicy") && getString("verifyDeviceStrategy", "").equals("solid");
    }

    public static boolean useLoadingView() {
        return getBoolean("useLoadingView");
    }

    public static boolean useRong() {
        return BuildConfigUtil.INSTANCE.getBoolean("useRong");
    }

    public static boolean useContact() {
        return getBoolean("useContact");
    }

    public static boolean useFileManager() {
        return getBoolean("useFileManager");
    }

    public static boolean useLogin() {
        return getBoolean("useLogin");
    }

    public static boolean useSetting() {
        return getBoolean("useSetting");
    }

    public static boolean useLock() {
        return getBoolean("useLock");
    }

    public static boolean useAppStore() {
        return getBoolean("useAppStore");
    }

    public static boolean useScheme() {
        return getBoolean("useScheme");
    }

    @Deprecated
    public static boolean useTheme() {
        return BuildConfigUtil.INSTANCE.getBoolean("useTheme");
    }

    public static boolean loginBackgroundIsFull() {
        return getBoolean("loginBackgroundIsFull",false);
    }

    public static boolean loginFontStyleIsDark() {
        return getBoolean("loginFontStyleIsDark");
    }

    public static String loginButtonColor() {
        return getString("loginButtonColor","");
    }


    public static String loginButtonTextColor() {
        return getString("loginButtonTextColor","");
    }

    public static boolean useHaikangMonitor() {
        return getBoolean("useHaikangMonitor");
    }

    public static int getWelcomeCount() {
        return getInt("welcomeCount", 0);
    }

    public static String getCodeVersion() {
        return getString("codeVersion","");
    }

    public static boolean useFaceID() {
        return getBoolean("FaceIDEnabled");
    }

    public static boolean isShowH5Menu() {
        return getBoolean("isShowH5Menu");
    }

    public static boolean isCollection() {
        return getBoolean("isCollection");
    }

    public static boolean useVoiceAssistant() {
        return getBoolean("useVoiceRecognize");
    }

    public static boolean useVPN() {
        return getBoolean("useVPN",false);
    }

    public static String getVPNAddress() {
        return getString("useVPN_Address", null);
    }

    public static String getVPNNtlsAddress() {
        return getString("useVPN_NtlsAddress", null);
    }

    public static String getVPNUsername() {
        return getString("useVPN_UserName", null);
    }

    public static String getVPNPassword() {
        return getString("useVPN_Password", null);
    }

    public static boolean showDisconnectVPNButton() {
        return getBoolean("showDisconnectVPNButton",false);
    }

    public static boolean webviewRotateEnable() {
        return getBoolean("webviewRotateEnable");
    }

    public static boolean useAppWidget() {
        return getBoolean("useAppWidget");
    }
}
